package com.wlt.controller;


import com.wlt.pojo.CartGoods;
import com.wlt.pojo.Orders;
import com.wlt.result.BaseResult;
import com.wlt.service.CartService;
import com.wlt.service.OrdersService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/orders")
public class OrdersController {
    @DubboReference
    private OrdersService ordersService;
    @DubboReference
    private CartService cartService;
    
    /**
     * 生成订单
     * @param orders    订单对象
     * @param userId    用户id
     * @return          生成的订单
     */
    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestBody Orders orders, @RequestHeader Long userId) {
        // 保存订单
        orders.setUserId(userId);
        ordersService.add(orders);
        
        // 将Redis中购物车的数据删除
        List<CartGoods> cartGoods = orders.getCartGoods();
        for (CartGoods cartGood : cartGoods) {
            cartService.deleteCart (userId, cartGood.getGoodId());
        }
        
        return BaseResult.success(orders);
    }
    
    /**
     * 根据id查询订单详情
     * @param id    订单id
     * @return      详情
     */
    @GetMapping("/findById")
    public BaseResult<Orders> findById (String id) {
        return BaseResult.success(ordersService.findById(id));
    }
    
    /**
     * 查询用户订单
     * @param status    订单状态：1.未付款 2.已付款 3.未发货 4.已发货 5.交易成功 6.交易关闭 7.待评价 null代表查询所有
     * @param userId    用户ID
     * @return          查询结果
     */
    @GetMapping("/findUserOrders")
    public BaseResult<List<Orders>> findUserOrders (Integer status, @RequestHeader Long userId) {
        return BaseResult.success(ordersService.findUserOrders(userId, status));
    }
}
